<?php
declare (strict_types = 1);
namespace app\course\model\classes\admin;

use app\common\model\payment\admin\PaymentOrderItem;
use app\common\model\payment\admin\PaymentTransaction;
use app\common\model\ProductType;
use app\school\model\school\School;
use app\user\model\user\Account;
use think\model\relation\BelongsTo;

/**
 * 班级课程订单--后台管理
 */
class Order extends PaymentOrderItem
{
    /**
     * 时间显示格式
     * @var string
     */
    protected $dateFormat = 'Y-m-d H:i';

    /**
     * 全局查询范围
     * @var [type]
     */
    protected $globalScope = ['mhm', 'product'];

    /**
     * 限制机构条件
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-06-16
     * @param    [type]                         $query [description]
     */
    public function scopeMhm($query)
    {
        // 如果不是平台时, 加入机构条件限制
        if (!request()->is_platform) {
            $query->where('__TABLE__.mhm_id', request()->mhm_id);
        }
    }
    /**
     * 产品类型
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-04
     * @param    [type]                         $query [description]
     */
    public function scopeProduct($query)
    {
        $query->where('product_type_id', ProductType::getProductIdByKey('classes'));
    }
    /**
     * 交易记录
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-04
     */
    public function transaction()
    {
        return $this->hasOne(PaymentTransaction::class, 'order_no', 'order_no');
    }

    /**
     * 机构
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-02
     */
    public function school(): BelongsTo
    {
        return $this->belongsTo(School::class, 'mhm_id')->bind(['school_name' => 'title']);
    }

    /**
     * 购买者
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-04
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'user_id')->removeOption('soft_delete')->removeWhereField('mhm_id');
    }

    /**
     * 产品名称
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-04
     */
    public function course(): BelongsTo
    {
        return $this->belongsTo(Classes::class, 'product_id')->with(['coverUrl'])->bind(['product_title' => 'title'])->removeOption('soft_delete');
    }
}
